package com.example.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;

import java.security.Key;
import java.util.Date;

public class JwtSuperUtil {

    /**
     * 密钥
     */
    private static final String secretKey = "TangRuoJie3177065378MySuperSecretKey1234567890";
    private static final Key key = Keys.hmacShaKeyFor(secretKey.getBytes());
    private static final long expiration = 1000 * 60 * 60 * 24;

    /**
     * 生成 token
     */
    public static String generateToken(String username) {
        return Jwts.builder()
                .setSubject(username)
                .claim("role", "TangRuoJie")
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + expiration))
                .signWith(key, SignatureAlgorithm.HS256)
                .compact();
    }

    /**
     * 解析 token
     */
    public static Claims parseToken(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(key)
                .build()
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 验证 token 是否过期或非法
     */
    public static boolean validateToken(String token) {
        try {
            return parseToken(token).getExpiration().after(new Date());
        } catch (Exception e) {
            return false;
        }
    }

}
